const User = require('../models/user')

class UserCtl {
    // 新增用户
    async register (ctx) {
        // 校验数据类型
        ctx.verifyParams({
            name: { type: 'string', required: true },
            password: { type: 'string', required: true }
        })
        const { name } = ctx.request.body
        const repeatedUser = await User.findOne({ name })
        if (repeatedUser) {
            ctx.throw(409, '用户已经存在')
        }
        const user = await new User(ctx.request.body).save()
        ctx.success({
            data: user
        })
    }
    async find (ctx) {
        const { name } = ctx.params
        const user = await User.findOne({ name: name })
        ctx.success({
            data: user
        })
    }
    async login (ctx) {
        ctx.verifyParams({
            name: { type: 'string', required: true },
            password: { type: 'string', required: true }
        })
        const user = await User.findOne(ctx.request.body)
        if (!user) { ctx.throw(401, '用户名或密码不正确') }
        const { _id, name } = user
        ctx.success({
            data: user
        })
    }
}

module.exports = new UserCtl()